package com.example.es_demo.controller;

import com.example.es_demo.dao.UserEntityRepository;
import com.example.es_demo.entity.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.awt.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

/**
 * @ClassName TestController
 * @Description TODO
 * @Author zhaoluowei
 * @Date 2019/6/29  17:14
 * @Version 1.0
 */

@RestController
@RequestMapping(value = "/test")
public class TestController {

    @Autowired
    private UserEntityRepository userEntityRepository;

    /**
     * 添加文档
     *
     * @param userEntity
     * @return
     */
    @PostMapping(value = "/addUser", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public UserEntity addUser(@RequestBody UserEntity userEntity) {
        //自动把对象专为json格式
        UserEntity entity = userEntityRepository.save(userEntity);

        return entity;
    }

    @PostMapping(value = "/getUserEntityById")
    public UserEntity getUserEntityById(Integer id) {
        Iterable<UserEntity> entities = userEntityRepository.findAllById(Collections.singleton(id));
        UserEntity entity = entities.iterator().next();

        return entity;
    }


    /**
     * 查询全部文档
     *
     * @return
     */
    @PostMapping(value = "/getAllDocument", produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public List<UserEntity> getAllDocument() {
        Iterable<UserEntity> repositoryAll = userEntityRepository.findAll();
        List<UserEntity> entityList = new ArrayList<>();
        if (entityList != null) {
            entityList.clear();
        }

        Iterator<UserEntity> iterator = repositoryAll.iterator();
        while (iterator.hasNext()) {
            entityList.add(iterator.next());
        }
        return entityList;
    }


}
